#! /bin/sh


dirs="builtin-functions"
set -x
d=gcov.$$
echo "output in $d/"
mkdir $d $d/builtin-functions
make clean  > $d/make-clean.log 2>&1
make EXTRA_CFLAGS="-fprofile-arcs -ftest-coverage" EXTRA_LDFLAGS="-fprofile-arcs -ftest-coverage" > $d/make.log 2>&1
./run-tests > $d/run-tests.log 2>&1
./run-tests -v --debug-all > $d/run-tests--debug-all.log 2>&1
for a in *.c ; do
  echo --- $a --- >> $d/gcov.output
  gcov $a >> $d/gcov.output 2>&1
done
for dir in $dirs ; do
  for a in $dir/*.c ; do
    echo --- $a --- >> $d/gcov.output

    if true; then
      ### HACK!!!!  gcov needs certain files to be in '.' but not all of them
      no_ext=`echo $a | sed -e 's/\\.c$//'`
      base_no_ext=`basename $no_ext`
      base=`basename $a`
      ln -s $no_ext.gcda .
      ln -s $no_ext.gcno .
      ln -s $a .
      gcov $a >> $d/gcov.output 2>&1
      rm $base_no_ext.gcda
      rm $base_no_ext.gcno
      rm $base
      mv $base.gcov $dir
    else
      ### This would work, if gcov's output always used the full path names
      ### consistently...
      gcov $a >> $d/gcov.output 2>&1
    fi
      
  done
done
mv *.c.gcov $d
rm *.gcda *.gcno
for dir in $dirs ; do
  mv $dir/*.c.gcov $d/$dir
  rm $dir/*.gcda $dir/*.gcno
done

make clean > /dev/null 2>&1

perl -e 'my $total = 0; my $executed = 0;
while (<STDIN>) { if (/Lines executed:\s*(\d*\.\d\d)% of (\d+)/) {
  my $percent = $1; my $lines = $2;
  $total += $lines;
  $executed += $lines * $percent / 100;
} }
$executed = int($executed);
$percent = sprintf("%.02f", int(10000 * $executed / $total)  / 100);
print "Executed $executed lines of $total ($percent%).\n"' < $d/gcov.output > $d/summary.output

perl -e 'my $total = 0; my $executed = 0;
sub pad($$) { $_[0] . (" " x ($_[1] - length($_[0]))) }
sub rpad($$) { (" " x ($_[1] - length($_[0]))) . $_[0]  }
while (<STDIN>) { if (/--- (.*) ---/) {
  my $fname = $1;
  scalar(<STDIN>);
  if (scalar(<STDIN>) =~ /Lines executed:\s*(\d*\.\d\d)% of (\d+)/) {
  my $percent = $1; my $lines = $2;
  $total += $lines;
  $executed = int($lines * $percent / 100);
  print join(" ",
            rpad($percent, 7),
            rpad($executed, 4),
            rpad($lines-$executed, 4),
            rpad($lines, 4),
            $fname) . "\n"
} } }
' < $d/gcov.output | sort -n > $d/file-summary.output


cat $d/summary.output

echo `date`: `cat $d/summary.output` >> coverage-history.txt

echo '[backgrounding make]' 1>&2

make > /dev/null 2>&1 &

